package com.liting.uitest.imgutils;

import com.liting.uitest.model.Circle;
import com.liting.uitest.model.ImageInfo;
import com.liting.uitest.model.Rectangle;
import com.liting.uitest.service.impl.ImageCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 平衡感计算
 */
@Service
public class Balance {
    @Autowired
    private ImageCacheService cacheService;

    public BigDecimal baCalc(Long fileId, List<Rectangle> rectList, List<Circle> cirList) throws Exception {
        ImageInfo imageInfo = cacheService.getImage(fileId);
        if (imageInfo == null) {
            throw new Exception("文件不存在");
        }

        double centerX = imageInfo.getWidth() / 2;
        double centerY = imageInfo.getHeight() / 2;

        BigDecimal leftW = new BigDecimal(0);
        BigDecimal rightW = new BigDecimal(0);
        BigDecimal topW = new BigDecimal(0);
        BigDecimal buttomW = new BigDecimal(0);

        //矩形计算
        for (Rectangle rectangle : rectList) {
            rectangle.splitFour(centerX, centerY);
            if (rectangle.getLeftRect() != null) {
                leftW = leftW.add(new BigDecimal(rectangle.getLeftRect().getDistance(centerX, centerY))
                        .multiply(rectangle.getLeftRect().getArea()));
            }
            if (rectangle.getRightRect() != null) {
                rightW = rightW.add(new BigDecimal(rectangle.getRightRect().getDistance(centerX, centerY))
                        .multiply(rectangle.getRightRect().getArea()));
            }
            if (rectangle.getTopRect() != null) {
                topW = topW.add(new BigDecimal(rectangle.getTopRect().getDistance(centerX, centerY))
                        .multiply(rectangle.getTopRect().getArea()));
            }
            if (rectangle.getButtomRect() != null) {
                buttomW = buttomW.add(new BigDecimal(rectangle.getButtomRect().getDistance(centerX, centerY))
                        .multiply(rectangle.getButtomRect().getArea()));
            }
        }

        //圆形暂不处理


        BigDecimal maxLR = new BigDecimal(0);
        if (leftW.compareTo(rightW) > 0) {
            maxLR = leftW;
        } else {
            maxLR = rightW;
        }

        BigDecimal maxTB = new BigDecimal(0);
        if (topW.compareTo(buttomW) > 0) {
            maxTB = topW;
        } else {
            maxTB = buttomW;
        }

        BigDecimal tempLR = leftW.subtract(rightW).divide(maxLR, BigDecimal.ROUND_HALF_UP).abs();
        BigDecimal tempTB = topW.subtract(buttomW).divide(maxTB, BigDecimal.ROUND_HALF_UP).abs();

        BigDecimal result = new BigDecimal(1).subtract((tempLR.add(tempTB)).divide(new BigDecimal(2), BigDecimal.ROUND_HALF_UP));

        return result.setScale(2, RoundingMode.UP);

    }
}
